<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" name>
  <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
</el-breadcrumb>
<el-card>
  <el-row>
    <el-col>
      <el-button type="primary" @click="addDialogVisiblee=true">添加角色</el-button>
    </el-col>
  </el-row>
  <el-table :data="roleslist" border stripe>
    <el-table-column type="expand">
      <template #default="{row}">
        <el-row :class="['bdbottom',i1 === 0 ? 'bdtop':'','vcenter']"  v-for="(item1,i1) in row.children" :key="item1.id">
        <el-col :span="5">
        <el-tag @close="removeRightById(row,item1.id)" closable>{{ item1.authName }}</el-tag>
        <i class="el-icon-caret-right"></i>
        </el-col>
        <el-col :span="19">
        <el-row :class="[i2 === 0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
          <el-col :span="6">
            <el-tag @close="removeRightById(row,item2.id)" closable type="success">{{ item2.authName }}</el-tag>
            <i class="el-icon-caret-right"></i>
          </el-col>
          <el-col :span="18">
          <el-tag @close="removeRightById(row,item3.id)" closable type="warning" v-for="(item3,i3) in item2.children" :key="item3.ud">
            {{ item3.authName }}
          </el-tag>
          </el-col>
        </el-row>
        </el-col>
      </el-row>
        <pre>{{row}}</pre>
      </template>
    </el-table-column>
    <el-table-column type="index" label="" ></el-table-column>
    <el-table-column label="角色名称" prop="roleName"></el-table-column>
    <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
    <el-table-column label="操作" width="280px">
      <template #default="{row}">
        <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialogg(row.id)">编辑</el-button>
        <el-button size="mini" type="danger" icon="el-icon-datele" @click="removeUserByIdd(row.id)">删除</el-button>
        <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(row)">分配权限</el-button>
      </template>
    </el-table-column>  
  </el-table>
</el-card>
<!-- 分配权限的对话 -->
<el-dialog
  title="分配权限"
  :visible.sync="setRightDialogVisble"
  width="50%"
  @close="setRightDialgClosed"
>
  <!-- <span>这是一段信息</span> -->
 <el-tree :data="rightslist" :props="terrProps" show-checkbox node-key="id" default-expand-all :default-expanded-keys="defKeys" ref="treeRef"> </el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
</el-dialog>
<!-- 添加用户 -->
<el-dialog
  title="添加用户"
  :visible.sync="addDialogVisiblee"
  width="50%"
  @close="addDialogClosedd"
  >
  <!-- <span>这是一段信息</span> -->
  <el-form :model="addFormm" :rules="addFormRuless" ref="addFormReff" label-width="80px">
    <!-- 用户名 -->
    <el-form-item label="角色名称" prop="usernamee">
    <el-input v-model="addFormm.usernamee"></el-input>
  </el-form-item>
      <!-- 密码 -->
      <el-form-item label="角色描述" prop="passwordd">
    <el-input v-model="addFormm.passwordd"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisiblee = false">取 消</el-button>
    <el-button type="primary" @click="addUserr">确 定</el-button>
  </span>
</el-dialog>
<!--修改用户 -->
<el-dialog
  title="修改用户"
  :visible.sync="editDialogVisiblee"
  width="50%"
  >
  <!-- <span>这是一段信息</span> -->
  <el-form :model="editFormm" :rules="editFormRuless" ref="editFormReff" label-width="70px">
    <el-form-item label="角色名称">
      <el-input v-model="editFormm.roleName"></el-input>
    </el-form-item>
    <el-form-item label="角色描述">
      <el-input v-model="editFormm.roleDesc"></el-input>
    </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="eidtUserInfoo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
// import { log } from 'console'
import {roles,bianId} from '@/api/user'
export default {
  data() {
    return {
      roleslist: [],
      setRightDialogVisble: false,
      rightslist: [],
      terrProps: {
        label: 'authName',
        children:'children'
      },
      defKeys:[],
      roleId: '',
      setRoleDialogVisible: false,
      addDialogVisiblee: false,
      addFormm: {
        usernamee: '',
        passwordd: '',
      },
      addFormRuless: {
      usernamee: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min:3,max:10,message:'长度在3到10个字符',trigger: 'blur'}
      ],
      passwordd: [
      { required: true, message: '请输入角色描述', trigger: 'blur' },
        { min:1,max:30,message:'长度在1到30个字符',trigger: 'blur'}
      ],
      },
      editDialogVisiblee: false,
      editFormm: {
        roleName: '',
        roleDesc:''
        
      },
      editFormRuless: {
        roleName: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min:3,max:10,message:'长度在3到10个字符',trigger: 'blur'}
      ],
      roleId: [
      { required: true, message: '请输入角色描述', trigger: 'blur' },
        { min:1,max:30,message:'长度在1到30个字符',trigger: 'blur'}
      ],
      }
    }
    
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色权限失败')
      }
      this.roleslist = res.data
      // console.log(this.roleslist);
    },
    async removeRightById(role,rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除文件，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // console.log('确定删除')
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      role.children = res.data
    },
    async showSetRightDialog(role) {
    this.roleId = role.id
     const { data: res } = await this.$http.get('rights/tree')
     if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
     }
     this.rightslist=res.data
     this.setRightDialogVisble = true
      this.getLeafKeys(role,this.defKeys)
    },
    getLeafKeys(node,arr) {
      if (!node.children) {
    // console.log(arr);
        return arr.push(node.id)
  }
      node.children.forEach(item =>this.getLeafKeys(item,arr))
    },
    setRightDialgClosed() {
      // console.log(defKeys);
      this.defKeys=[]
    },
  async  allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
    const idStr = keys.join(',')
    const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
    if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
    }
    this.$message.success('分配权限成功')
    this.getRolesList()
      this.setRightDialogVisble=false
    },
   async addUserr() {
    this.$refs.addFormReff.validate(async valid => {
        if (!valid) return
        const {data: res} = await this.$http.post('roles',{roleName:this.addFormm.roleName,roleDesc:this.addFormm.roleId})
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisiblee = false
        this.getRolesList()
      })
    },
    addDialogClosedd() {
      this.$refs.addFormReff.resetFields()
    },
   async showEditDialogg(id) {
      const {data:res}=await this.$http.get('roles/' + id)
     if (res.meta.status !== 200) {
       return this.$message.error('查询失败')
     }
     this.editFormm = res.data
      // console.log(this.editFormm);
      this. editDialogVisiblee = true
    },
   async eidtUserInfoo() {
      // console.log(this.editFormm);
    const res =  await bianId(this.editFormm.roleId,this.editFormm)
    //  console.log(res);
    //  console.log(this.editFormm.roleId, this.editFormm);
    this.$message.success('更新成功')
     this.getRolesList()
     this.editDialogVisiblee = false

      // this.$refs.editFormReff.validate(async valid => {
      //   if (!valid) return
      //   const {data:res}=await this.$http.put('roles/' + this.editFormm.id,{roleName:this.addFormm.usernamee,roleDesc:this.addFormm.passwordd})
      //   if (res.meta.status !== 200) {
      //     return this.$message.error('更新失败')
      //   }
      //   this.editDialogVisiblee = false
      //   this.getRolesList()
      //   this.$message.success('更新成功')
      // })
    },
    async removeUserByIdd() {
      const confirmResultt = await this.$confirm('此操作将删除用户,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type:'warning'
      }).catch(err => err)
      if (confirmResultt !== 'confirm') {
        return this.$message.info('取消删除')
      }
      this.$message.success('删除成功')
      this.getRolesList()
    }
  
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>